package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.TrainPromoteLookTeacher;
import com.xmy.cultivate.entity.TeacherPoint;
import com.xmy.cultivate.entity.TrainPromoteLookTeacher;
import com.xmy.cultivate.service.ITrainPromoteLookTeacherService;
import com.xmy.cultivate.service.ITrainPromoteLookTeacherService;
import com.xmy.cultivate.service.TeacherPointService;
import com.xmy.cultivate.util.*;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 资料查看教师 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-11-01
 */
@RestController
@RequestMapping("/api/trainPromoteLookTeacher")
public class TrainPromoteLookTeacherController extends BaseController {

    @Autowired
    TeacherPointService teacherPointService;

    @Autowired
    ITrainPromoteLookTeacherService iTrainPromoteLookTeacherService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    /**
     * 资料查看教师列表
     */
    @GetMapping("")
    public Result findAllPage(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                              @RequestParam(value = "export", defaultValue = "0", required = false) Integer export,
                              @RequestParam(value = "yearPart", required = false) String yearPart,  //年份
                              @RequestParam(value = "quarterNum", required = false) String quarterNum, //学期
                              @RequestParam(value = "lessonType", required = false) String lessonType, //课程类型
                              @RequestParam(value = "teacherName", required = false) String teacherName,  //教师
                              @RequestParam(value = "yearClassId", required = false) String yearClassId,     //年级ID
                              @RequestParam(value = "courseTypeId", required = false) String courseTypeId,     //班型
                              @RequestParam(value = "subjectId", required = false) String subjectId,     //科目
                              @RequestParam(value = "type", required = false) String type,
                              @RequestParam(value = "teacherType", required = false) String teacherType, // 1主备，2非主备
                              @RequestParam(value = "versionId", required = false) String versionId // 版本id
    ) throws IOException {
        IPage<TeacherPoint> iPage = new Page<>(pageNum, pageSize);
        iTrainPromoteLookTeacherService.findAll(iPage, yearPart, quarterNum, lessonType, teacherName, yearClassId, courseTypeId, subjectId, type, teacherType, versionId);

        if (export == 1) {
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("教学积分");
            CellStyle headerCellStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setFontHeightInPoints((short) 11);
            headerCellStyle.setFont(headerFont);
            headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
            headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            Row headerRow = sheet.createRow(0);
            sheet.createFreezePane(0, 1);// 冻结首行

            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFont(headerFont);
            cellStyle.setAlignment(HorizontalAlignment.CENTER);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            List<String> headList = new ArrayList<>();
            headList.add("年份");
            headList.add("学期");
            headList.add("教师");
            headList.add("课程类型");
            headList.add("备课类型");
            headList.add("项目类型");
            headList.add("年级");
            headList.add("班型");
            for (int i = 0; i < headList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(headerCellStyle);
            }
            int rowIndex = 1;// 数据行起始索引
            for (TeacherPoint teacherPoint : iPage.getRecords()) {
                Row row = sheet.createRow(rowIndex++);

                Cell cell1 = row.createCell(0);
                cell1.setCellValue(teacherPoint.getYearPart());
                sheet.setColumnWidth(0, 15 * 256);
                cell1.setCellStyle(cellStyle);

                Cell cell2 = row.createCell(1);
                cell2.setCellValue(CommonUtil.getQuarterNameForId(teacherPoint.getQuarterNum()));
                sheet.setColumnWidth(1, 15 * 256);
                cell2.setCellStyle(cellStyle);

                Cell cell3 = row.createCell(2);
                if (teacherPoint.getTeacherName() != null) {
                    cell3.setCellValue(teacherPoint.getTeacherName());
                } else {
                    cell3.setCellValue("");
                }
                sheet.setColumnWidth(2, 15 * 256);
                cell3.setCellStyle(cellStyle);

                Cell cell4 = row.createCell(3);
                if (teacherPoint.getLessonTypeName() != null) {
                    cell4.setCellValue(teacherPoint.getLessonTypeName());
                } else {
                    cell4.setCellValue("");
                }
                sheet.setColumnWidth(3, 15 * 256);
                cell4.setCellStyle(cellStyle);

                Cell cell9 = row.createCell(4);
                if (teacherPoint.getTeacherType() != null) {
                    if (teacherPoint.getTeacherType().equals(1)) {
                        cell9.setCellValue("主备");
                    } else {
                        cell9.setCellValue("非主备");
                    }
                } else {
                    cell9.setCellValue("");
                }
                sheet.setColumnWidth(4, 15 * 256);
                cell9.setCellStyle(cellStyle);

                Cell cell8 = row.createCell(5);
                if (teacherPoint.getTypeStr() != null) {
                    cell8.setCellValue(teacherPoint.getTypeStr());
                } else {
                    cell8.setCellValue("");
                }
                sheet.setColumnWidth(5, 15 * 256);
                cell8.setCellStyle(cellStyle);

                Cell cell5 = row.createCell(6);
                cell5.setCellValue(CommonUtil.getYearClassNameForId(teacherPoint.getGrade()));
                sheet.setColumnWidth(6, 15 * 256);
                cell5.setCellStyle(cellStyle);

                Cell cell6 = row.createCell(7);
                cell6.setCellValue(teacherPoint.getCourseType());
                sheet.setColumnWidth(7, 60 * 256);
                cell6.setCellStyle(cellStyle);
            }

            String fileName = "备课练课" + ".xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");

            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
            // 获取响应输出流
            OutputStream outputStream = response.getOutputStream();
            // 将工作簿写入输出流
            workbook.write(outputStream);
            // 关闭工作簿
            workbook.close();
            // 刷新输出流
            outputStream.flush();
            //关闭输出流
            outputStream.close();

        }
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 资料查看教师添加
     */
    @PostMapping("/save")
    public Result saveTrainPromoteLookTeacher(@RequestBody TrainPromoteLookTeacher practiceBrushTeacher) {
        if (practiceBrushTeacher.getLessonType() == null) {
            practiceBrushTeacher.setLessonType(1);
        }
        if (practiceBrushTeacher.getTeacherType() == null) {
            practiceBrushTeacher.setTeacherType(1);
        }

        for (String type : practiceBrushTeacher.getTypeStr()) {
            for (String courseTypeId : practiceBrushTeacher.getCourseTypeIdStr()) {
                QueryWrapper<TrainPromoteLookTeacher> teacherPointWrapper = new QueryWrapper<>();
                teacherPointWrapper.eq("year_part", practiceBrushTeacher.getYearPart());
                teacherPointWrapper.eq("quarter_num", practiceBrushTeacher.getQuarterNum());
                teacherPointWrapper.eq("type", type);
                teacherPointWrapper.eq("teacher_type", practiceBrushTeacher.getTeacherType());
                teacherPointWrapper.eq("teacher_id", practiceBrushTeacher.getTeacherId());
                teacherPointWrapper.eq("subjects_id", practiceBrushTeacher.getSubjectsId());
                teacherPointWrapper.eq("year_class_id", practiceBrushTeacher.getYearClassId());
                teacherPointWrapper.eq("course_type_id", courseTypeId);
                teacherPointWrapper.eq("lesson_type", practiceBrushTeacher.getLessonType());
                teacherPointWrapper.eq("version_id", practiceBrushTeacher.getVersionId());
                long practiceCount = iTrainPromoteLookTeacherService.count(teacherPointWrapper);
                if (practiceCount > 0) {
                    continue;
                }

                TrainPromoteLookTeacher brushTeacher = new TrainPromoteLookTeacher();
                BeanUtils.copyProperties(practiceBrushTeacher, brushTeacher);
                brushTeacher.setType(Integer.valueOf(type));
                brushTeacher.setCourseTypeId(Long.valueOf(courseTypeId));
                brushTeacher.setId(idWorker.nextId());

                iTrainPromoteLookTeacherService.save(brushTeacher);
            }
        }

        return new Result(Code.OK, "", "添加成功");
    }

    /**
     * 资料查看教师编辑
     */
    @PutMapping("/update")
    public Result updateTrainPromoteLookTeacher(@RequestBody TrainPromoteLookTeacher practiceBrushTeacher) {
        QueryWrapper removeWrapper = new QueryWrapper();
        removeWrapper.inSql("id", practiceBrushTeacher.getIdStr());
        iTrainPromoteLookTeacherService.remove(removeWrapper);

        for (String courseTypeId : practiceBrushTeacher.getCourseTypeIdStr()) {
            TrainPromoteLookTeacher brushTeacher = new TrainPromoteLookTeacher();
            BeanUtils.copyProperties(practiceBrushTeacher, brushTeacher);
            brushTeacher.setId(idWorker.nextId());
            brushTeacher.setCourseTypeId(Long.valueOf(courseTypeId));
            iTrainPromoteLookTeacherService.save(brushTeacher);
        }

        return new Result(Code.UPDATE_OK, "", "编辑成功");
    }

    /**
     * 资料查看教师删除
     */
    @PutMapping("/del")
    public Result deleteTrainPromoteLookTeacher(@RequestBody TrainPromoteLookTeacher practiceBrushTeacher) {
        iTrainPromoteLookTeacherService.remove(new QueryWrapper<>(practiceBrushTeacher).inSql("id", practiceBrushTeacher.getIdStr()));
        return new Result(Code.UPDATE_OK, "", "删除成功");
    }


}
